package com.ruoyi.zsyh.controller.applet.agent;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.wx.WXPayConfig;
import com.ruoyi.common.utils.wx.WXPayRequest;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author yuexl
 */
@Controller
@RequestMapping("/applet/zsyh/aliPay/")
public class AliPaymentController {

    private Logger logger = LoggerFactory.getLogger(AliPaymentController.class);


    @Value("${alipay.transferAppID}")
    private String transferAppID;

    @Value("${alipay.transferPrivateKey}")
    private String transferPrivateKey;

    @Value("${alipay.transferAlipayPublicKey}")
    private String transferAlipayPublicKey;

    @Autowired
    private IZsyhAfterFactoryBalanceService zsyhAfterFactoryBalanceService;

    @Autowired
    private IZsyhAfterFactoryService zsyhAfterFactoryService;

    @Resource
    private QgAlipayService qgAlipayService;


    /**
     * 厂家充值 充值回调
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/notifyUrlAfterFactoryRechargeAli", method = RequestMethod.POST)
    @ResponseBody
    public String notifyUrlAfterFactoryRechargeAli(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map requestParams = request.getParameterMap();
        request.setCharacterEncoding("UTF-8");

        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //支付宝交易号
        String trade_no = request.getParameter("trade_no");
        //订单金额
        String total_amount = request.getParameter("total_amount");
        logger.info("out_trade_no====================================" + out_trade_no);
        logger.info("trade_no====================================" + trade_no);
        logger.info("total_amount====================================" + total_amount);

        boolean verify_result = qgAlipayService.syncVerifyResult(requestParams);
        if (verify_result) {// 验证成功

            BigDecimal totalFee = new BigDecimal(total_amount);

            ZsyhAfterFactoryBalance factoryBalance = zsyhAfterFactoryBalanceService.selectZsyhAfterFactoryBalanceByBalanceRechargeState(out_trade_no);

            ZsyhAfterFactoryBalance factoryBalance1 = new ZsyhAfterFactoryBalance();
            factoryBalance1.setId(factoryBalance.getId());


            String balanceClassify = factoryBalance.getBalanceClassify();//分类 1保证金明细 2余额明细
            String factoryId = factoryBalance.getFactoryId();
            ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
            ZsyhAfterFactory factory1 = new ZsyhAfterFactory();
            factory1.setId(factoryId);

            BigDecimal factoryAll = factory.getFactoryAll();//厂家账户充值总金额
            BigDecimal balance = factory.getFactoryBalance();//厂家账户可用余额
            BigDecimal factoryMoney = factory.getFactoryMoney();//厂家账户保证金
            factoryBalance1.setBalancePayNum(trade_no);
            factoryBalance1.setBalanceRechargeState("1");

            if("1".equals(balanceClassify)){
                factory1.setFactoryMoney(factoryMoney.add(totalFee).setScale(2, BigDecimal.ROUND_HALF_UP));
                factoryBalance1.setBalanceMoneyAfter(factory1.getFactoryMoney());
            }else{
                factory1.setFactoryBalance(balance.add(totalFee).setScale(2, BigDecimal.ROUND_HALF_UP));
                factory1.setFactoryAll(factoryAll.add(totalFee).setScale(2, BigDecimal.ROUND_HALF_UP));
                factoryBalance1.setBalanceMoneyAfter(factory1.getFactoryBalance());
            }

            zsyhAfterFactoryBalanceService.updateZsyhAfterFactoryBalance(factoryBalance1);
            zsyhAfterFactoryService.updateZsyhAfterFactory(factory1);


            response.getWriter().println("success"); // 请不要修改或删除
        } else {// 验证失败
            response.getWriter().println("fail");
        }

        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;
        String returnxml = "";
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        //以字节流的形式读取request中的数据
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        params = WXPayUtil.xmlToMap(sb.toString());
        logger.info("1.notify-params>>>>>>>>>>>:" + params);

        String returnCode = params.get("return_code");
        logger.info("3.returnCode:" + returnCode);
        if (returnCode.equals("SUCCESS")) {
            //判断签名是否正确
            boolean flag = true;
            logger.info("2.notify-flag:" + flag);
            if (flag) {
                //获取微信订单号
                String transactionId = params.get("transaction_id");
                //获取商户订单号
                String outTradeNo = params.get("out_trade_no");

                String total_fee = params.get("total_fee");//支付金额

                //附加信息原路返回 厂家id
                String attach = params.get("attach");
                logger.info("transactionId====================================" + transactionId);
                logger.info("outTradeNo====================================" + outTradeNo);
                logger.info("attach====================================" + attach);
                logger.info("total_fee====================================" + total_fee);
                logger.info("outTradeNo====================================" + outTradeNo);
                //TODO 充值成功，保存余额明细，增加余额

                Double total = Double.valueOf(total_fee) * 0.01;



                result.put("return_code", "SUCCESS");
                result.put("return_msg", "支付成功");
                logger.info("4.订单：" + outTradeNo + " 交易完成" + ">>>" + transactionId);
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "签名失败");
                logger.error("签名验证失败>>>>>>>>>>>>");
            }
        } else {
            result.put("return_code", "FAIL");
            result.put("return_msg", "支付失败");
            logger.error("");
        }


        returnxml = WXPayUtil.mapToXml(result);
        return returnxml;
    }


}
